package cake.srcprojector.parser;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cake.srcprojector.DocParser;
import cake.srcprojector.DocParserContext;
import cake.srcprojector.model.Page;
import cake.srcprojector.model.SubPage;
import cake.srcprojector.service.PageService;


public class InitDocParser implements DocParser {

	private PageService pageService = new PageService();
	

	@Override
	public void startFolder(File folder, DocParserContext docParserContext) throws IOException {
	}
	

	@Override
	public void parsePage(File pageFile, File[] subFolderArray, DocParserContext docParserContext) throws IOException {
		// Initialise list of sub pages
		List<SubPage> subPageList = new ArrayList<SubPage>();
		for (File subFolder : subFolderArray) {
			
			File subPageFile = new File(subFolder, docParserContext.getPageFileName());
			
			// If the sub page is ready to be parsed
			if (subPageFile.length() > 0) {
				Page subPage = pageService.parsePage(subPageFile);
				subPageList.add(new SubPage(subPage.getPageId(), subPage.getTitle()));
			}
			
		}
		
		Page page = null;
		
		// If the file is empty
		if (pageFile.length() == 0) {
			page = new Page(java.util.UUID.randomUUID().toString(), "New Page");
		} else {
			page = pageService.parsePage(pageFile);
		}
		
		page.setSubPageList(subPageList);
		
		pageService.writePage(page, pageFile);
	}
	

	@Override
	public void endFolder(File folder, boolean isLast) throws IOException {
	}


	@Override
	public void start() throws IOException {
	}


	@Override
	public void end() throws IOException {
	}

	
}
